<?php

namespace App\Supports\Auth\Alipay;

use Exception;
use App\Models\User;
use App\Events\NewUserRegisteredEvent;
use Illuminate\Validation\ValidationException;

class AlipayLogger extends AlipayAuthUser
{
	protected $authData;
	
	public function httpValidate()
	{
		request()->validate(['code' => 'required|string']);
		
		$code = request('code');
		
		try {
			$accessToken = $this->getAccessTokenFromCode($code);
			$this->authData = $this->getUserFromToken($accessToken);
			if ($this->isAlipayBound()) {
				throw ValidationException::withMessages(['code' => '支付宝已被其它账号绑定']);
			}
		} catch (Exception $e) {
			throw ValidationException::withMessages(['code' => '参数错误，无法获取用户信息']);
		}
	}
	
	public function isAlipayBound()
	{
		$data = $this->authData;
		$alipayUserId = $data['user_id'] ?? '';
		
		$boundUser = null;
		if ($alipayUserId) {
			$boundUser = User::where('alipay_user_id', $alipayUserId)->first();
		}
		
		return $boundUser ? true : false;
	}
	
	protected function authNew()
	{
		$data = $this->authData;
		
		return User::create([
			'grade' => 'normal',
			'name' => isset($data['nick_name']) ? $data['nick_name'] : null,
			'avatar' => isset($data['avatar']) ? $data['avatar'] : null,
			'alipay_user_id' => $data['user_id'],
			'alipay_nickname' => isset($data['nick_name']) ? $data['nick_name'] : null,
			'alipay_avatar' => isset($data['avatar']) ? $data['avatar'] : null,
			'alipay_province' => isset($data['province']) ? $data['province'] : null,
			'alipay_city' => isset($data['city']) ? $data['city'] : null,
		]);
	}
	
	protected function auth()
	{
		$this->httpValidate();
		
		$alipayUserId = $this->authData['user_id'] ?? '';
		
		$user = User::where('alipay_user_id', $alipayUserId)->first();
		
		if (! $user) {
			$user = $this->authNew();
			event(new NewUserRegisteredEvent($user));
			return $user;
		}
		
		return $user;
	}
	
	public function login()
	{
		return $this->auth();
	}
}
